﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Pampa.CRUD.Exceptions;
using log4net;
using log4net.Repository.Hierarchy;

namespace Pampa.MVC.Controllers
{
    public abstract class AbstractController : Controller
    {
        protected JsonResult BuildResponse(Func<object> action)
        {
            try
            {
                var result = action.Invoke();
                return Json(new { value = result });
            }
            catch (SessionExpiratedException ex)
            {
                LogError(ex.Message);
                return Json(new { error = SessionExpiredMessage, expired = true });
            }
            catch (ValidationException ex)
            {
                return Json(new { error = ex.Message });
            }
            catch (Exception ex)
            {
                LogError(ex.Message);
                return Json(new { error = UnknowErrorMessage });
            }
        }

        protected JsonResult BuildResponse(Action action)
        {
            try
            {
                action.Invoke();
                return Json(new { });
            }
            catch (SessionExpiratedException ex)
            {
                LogError(ex.Message);
                return Json(new { error = SessionExpiredMessage, expired = true });
            }
            catch (Exception ex)
            {
                LogError(ex.Message);
                return Json(new { error = UnknowErrorMessage });
            }
        }

        private void LogError(string message)
        {
            var logger = LogManager.GetLogger("PampaMVC");
            logger.Error(message);
        }

        public static string SessionExpiredMessage
        {
            get; set;
        }

        public static string UnknowErrorMessage
        {
            get;
            set;
        }
    }
}
